<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">

    <title>购课清单统计查询</title>
    <script src="../static/js/common.js"></script>
    <script src="/static/js/moment.min.js"></script>
    <style>
        .date-container {
            margin: 20px;
        }
        .date-input {
            margin: 0 10px;
            padding: 5px;
        }
        .query-btn {
            margin: 10px;
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .query-btn:hover {
            background-color: #45a049;
        }
        .tables-container {
            margin: 20px;
        }
        .table-wrapper {
            margin-bottom: 30px;
        }
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        .data-table th, .data-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .data-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .data-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .data-table tr:hover {
            background-color: #f1f1f1;
        }
    </style>
</head>
<body>
    {% include 'show_ins_info.html' %}
    <link rel="stylesheet" href="../static/css/minghu.css">
    <h1>购课清单统计查询</h1>
    <div class="date-container">
        <label for="start-date">查询起始日:</label>
        <input type="date" id="start-date" class="date-input">
        
        <label for="end-date">查询结束日:</label>
        <input type="date" id="end-date" class="date-input">
        
        <button id="query-month" class="query-btn">查询本月</button>
    </div>

    <script>
        let insId;
        let insName;
        let insRole;

        document.addEventListener('DOMContentLoaded', function() {
            // loginCheck();

            //增加返回上一页按钮
            addGoLastPageBtn();            

            const insInfos=hideInsSelectBlockAndGetInsInfo();
            insId=insInfos['sessionInsId'];
            insName=insInfos['sessionInsName'];
            insRole=insInfos['sessionInsRole'];

            // Set default dates to today
            const today = moment().format('YYYY-MM-DD');
            document.getElementById('start-date').value = today;
            document.getElementById('end-date').value = today;
            
            // Validate end date >= start date
            const dateInputs = document.querySelectorAll('#start-date, #end-date');
            dateInputs.forEach(input => {
                input.addEventListener('change', function() {
                    const startDate = document.getElementById('start-date').value;
                    const endDate = document.getElementById('end-date').value;
                    
                    if (startDate && endDate && endDate < startDate) {
                        alert('结束日期不能小于起始日期');
                        document.getElementById('end-date').value = startDate;
                    }
                    fetchBuyList();
                });
            });
            
            // Query this month button
            document.getElementById('query-month').addEventListener('click', function() {
                const today = moment();
                const monthStart = today.clone().startOf('month').format('YYYY-MM-DD');
                const monthEnd = today.clone().endOf('month').format('YYYY-MM-DD');
                document.getElementById('start-date').value = monthStart;
                document.getElementById('end-date').value = monthEnd;
                fetchBuyList();
            });
            
            // Fetch buy list data
            function fetchBuyList() {
                const startDate = document.getElementById('start-date').value;
                const endDate = document.getElementById('end-date').value;

                fetch('/get_buy_list', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        start_date: startDate,
                        end_date: endDate
                    })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Data received:', data);
                    if (data && data.combine_data && data.raw_data) {
                        renderTables(data);
                    } else {
                        console.error('Invalid data format:', data);
                        // Clear previous tables if any
                        const oldContainer = document.querySelector('.tables-container');
                        if (oldContainer) {
                            oldContainer.remove();
                        }
                    }
                })
                .catch(error => console.error('Error:', error));
            }

            // Render tables from response data
            function renderTables(data) {
                const container = document.createElement('div');
                container.className = 'tables-container';
                
                // Create combined data table
                const combineTable = createTable(
                    '按日期合并的购买记录', 
                    ['购买日期', '估算实际实收', '客户ID/姓名/购买流水号', '应收金额', '实收金额'], 
                    Array.isArray(data.combine_data) ? data.combine_data.map(item => [
                        new Date(item.buy_date).toLocaleDateString(),
                        item.real_real_pay,
                        item.cus_id_name_buy_flow_id.replace(/;/g, '<br>'),
                        item.pay,
                        item.real_pay
                    ]) : []);

                // Create raw data table
                const rawTable = createTable(
                    '详细购买记录', 
                    ['序号', '购买日期', '客户ID', '客户姓名', '流水号', '卡号', '收银员', '备注', '应收金额', '实收金额'], 
                    Array.isArray(data.raw_data) ? data.raw_data.map((item, index) => [
                        index + 1,
                        new Date(item.buy_date).toLocaleDateString(),
                        item.cus_id,
                        item.cus_name,
                        item.buy_flow_id,
                        item.card_id,
                        item.cashier_name,
                        item.comment || '',
                        item.pay,
                        item.real_pay
                    ]) : []);

                // Clear previous tables if any
                const oldContainer = document.querySelector('.tables-container');
                if (oldContainer) {
                    oldContainer.remove();
                }

                container.appendChild(combineTable);
                container.appendChild(rawTable);
                document.body.appendChild(container);
            }

            // Helper function to create a table
            function createTable(title, headers, rows) {
                const tableDiv = document.createElement('div');
                tableDiv.className = 'table-wrapper';
                
                const titleEl = document.createElement('h3');
                titleEl.textContent = title;
                tableDiv.appendChild(titleEl);

                const table = document.createElement('table');
                table.className = 'data-table';
                
                // Create header
                const thead = document.createElement('thead');
                const headerRow = document.createElement('tr');
                headers.forEach(headerText => {
                    const th = document.createElement('th');
                    th.textContent = headerText;
                    headerRow.appendChild(th);
                });
                thead.appendChild(headerRow);
                table.appendChild(thead);
                
                // Create body
                const tbody = document.createElement('tbody');
                rows.forEach(rowData => {
                    const row = document.createElement('tr');
                    rowData.forEach(cellData => {
                        const td = document.createElement('td');
                        td.innerHTML = cellData;
                        row.appendChild(td);
                    });
                    tbody.appendChild(row);
                });
                table.appendChild(tbody);
                
                tableDiv.appendChild(table);
                return tableDiv;
            }
            
            // Initial fetch on page load
            fetchBuyList();
        });
    </script>
</body>
</html>
